"""Generate an html document from an msig output file and output that.

This function alows a user to take an output file from an msig analysis and remake that into some kind of html that has more user interfaces compared with the original file.  This will allow things like searching and linking to other files all viewable from the comfort of a standard web browser.

"""

import sys, os, re

def makeFilterBlock():
    return """

<script type="text/javascript">
function filter2 (phrase, _id){
    var words = phrase.value.toLowerCase().split(" ");
    var table = document.getElementById(_id);
    var ele;
    for (var r = 1; r < table.rows.length; r++){
        ele = table.rows[r].innerHTML.replace(/<[^>]+>/g,"");
            var displayStyle = 'none';
            for (var i = 0; i < words.length; i++) {
            if (ele.toLowerCase().indexOf(words[i])>=0)
            displayStyle = '';
            else {
            displayStyle = 'none';
            break;
            }
            }
        table.rows[r].style.display = displayStyle;
    }
}
</script>

"""


def parseTable(mg, tid):
    """Takes a mg (str) and generates an html table from it that is searchable"""
    mg = mg.strip() # we strip the text just to make sure that there are no extra spaces or returns
    if mg == '': return ''
    print mg[:200]
    lines = mg.split('\n') #split by lines
    print lines[:2]
    newtext = """<form><b>Filter Table By:</b> <input name="filt" onkeyup="filter2(this, '%s', '1')" type="text"></form><br> <TABLE id="%s" WIDTH="100%%" BORDER="0" CELLSPACING="1" CELLPADDING="2"><TR BGCOLOR="">""" % (str(tid), str(tid))
    if re.match(r'\s*Gene Symbol', mg) != None:
        for w in lines[0].split('\t'):
            newtext += '<TD ALIGN="MIDDLE"><FONT COLOR=""><B>%(colname)s</B></FONT></TD>' % {'colname':w.strip().replace('_', ' ')}
        newtext += '<TD ALIGN="MIDDLE"><FONT COLOR=""><B>Number of Hits</B></FONT></TD>'
        newtext += "</TR>"
        for l in lines[1:]:
            vals = l.split('\t')
            newtext += '<TR BGCOLOR="#FFFFFF">'
            newtext += '<TD><a href="http://www.ncbi.nlm.nih.gov/gene?term=%s">%s</a></TD>' % (vals[0], vals[0])
            newtext += '<TD>%s</TD>' % vals[1]
            for w in vals[2:]:
                if w.strip() != '':
                    newtext += '<TD BGCOLOR="#1111FF"><small>%s</small></TD>' % w.replace('_', ' ')
                else:
                    newtext += '<TD BGCOLOR="#FFFFFF"></TD>'
            newtext += '<TD>%s</TD>' % str(len([a for a in vals[2:] if a != '']))
            newtext += '</TR>'
    else:
        for w in lines[0].split('\t'):
            newtext += '<TD ALIGN="MIDDLE"><FONT COLOR=""><B>%(colname)s</B></FONT></TD>' % {'colname':w.strip()}
        newtext += "</TR>"
        for l in lines[1:]:
            newtext += '<TR BGCOLOR="#FFFFFF">'
            for w in l.split('\t'):
                newtext += '<TD>%s</TD>' % w.strip()
            newtext += '</TR>'
    
    newtext += '</TABLE>'
    return newtext
    

def parseFile(fn):
    with open(fn, 'r') as f:
        ftext = f.read()
    newtext = """

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<title>KRC MSigDB Results Output</title>
<body bgcolor="#FFEEEE">
<center>
<h1>KRC MSigDB Results Output</h1>
</center>

<script type="text/javascript">
function filter2 (phrase, _id){
    var words = phrase.value.toLowerCase().split(" ");
    var table = document.getElementById(_id);
    var ele;
    for (var r = 1; r < table.rows.length; r++){
        ele = table.rows[r].innerHTML.replace(/<[^>]+>/g,"");
            var displayStyle = 'none';
            for (var i = 0; i < words.length; i++) {
            if (ele.toLowerCase().indexOf(words[i])>=0)
            displayStyle = '';
            else {
            displayStyle = 'none';
            break;
            }
            }
        table.rows[r].style.display = displayStyle;
    }
}
</script>

<p>
This is modified output from an MSigDB overlap file.  I have modified the file so that it is more interactive and gives a nicer user experience than the original file.  If you really like this output then you should contact MSigDB and tell them that their output is bad and this one should be sent in it's place.
</p>

"""
    
    tableid = 1
    for mg in  re.finditer(r'.*?(\n\n)|.*', ftext, re.DOTALL):
        print mg.group()[:400], "End block"
        if 'Overlap Results' in mg.group()[:20]: continue
        elif 'Gene/Gene Set' in mg.group()[:20]: continue
        elif re.match(r'\s*Collection\(s\):', mg.group(), re.DOTALL) != None:
            newtext += '<pre>' + '<br>'.join(mg.group().split('\n')) + '</pre><br>'
            print newtext[-200:]
        else:
            newtext += parseTable(mg.group(), 'table'+str(tableid))
            tableid += 1

    newtext += "</body></html>"

    with open(os.path.splitext(fn)[0] + '.html', 'w') as f:
        f.write(newtext)

parseFile(sys.argv[1])

    
    